/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.videodes.desktop;

import cz.muni.fi.pb138.videodes.entity.Genre;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.TransferHandler;

/*
 * GenreListTransferHandler.java is used by the DropDemo example.
 */
public class GenreListTransferHandler extends TransferHandler {

    @Override
    protected Transferable createTransferable(JComponent c) {
        return new StringSelection((String) ((JList) c).getSelectedValue().toString());
    }

    @Override
    public int getSourceActions(JComponent c) {
        return TransferHandler.MOVE;
    }

    @Override
    public boolean canImport(TransferHandler.TransferSupport info) {
        return true;
    }

    @Override
    public boolean importData(TransferHandler.TransferSupport info) {
        if (!info.isDrop()) {
            return false;
        }

        JList list = (JList) info.getComponent();
        GenreListModel listModel = (GenreListModel) list.getModel();

        // Get the string that is being dropped.
        Transferable t = info.getTransferable();
        String data;
        try {
            data = (String) t.getTransferData(DataFlavor.stringFlavor);
        } catch (Exception e) {
            return false;
        }

        // Perform the actual import.  
        listModel.add(Genre.valueOf(data.trim()));
        return true;
    }

    @Override
    protected void exportDone(JComponent c, Transferable data, int action) {
        if (action == TransferHandler.MOVE) {
            JList source = (JList) c;
            GenreListModel model = (GenreListModel) source.getModel();
            model.remove((Genre) source.getSelectedValue());
        }
    }
}